<?php
/**
 * 快钱支付 控制器类
 */
namespace Home\Controller;
use Think\Controller;
class KuaiqianPayController extends Controller{
	/**
	 * 充值回调处理
	 */
	public function notify_url(){

		// 支付配置
		$pay_config = D('Config')->get('', 'pay');
		// 去掉TP的GET参数
		unset($_REQUEST['_URL_']);
		import("KuaiQianPayService",'Public/Class/Pay/KuaiQian');
		$cert_path        = D('File')->get_file_info($pay_config['kuaiqian_cer_path'], 'filepath');
		$pem_path         = D('File')->get_file_info($pay_config['kuaiqian_pem_path'], 'filepath');
		$pay = new \KuaiQianPayService($cert_path, $pem_path);
		$pay->merchant_id      = $pay_config['kuaiqian_merchant_id'];
		$pay->vpos_merchant_id = $pay_config['kuaiqian_vpos_merchant_id'];
		$pay->soap_merchant_id = $pay_config['kuaiqian_soap_merchant_id'];
		$pay->terminal_id      = $pay_config['kuaiqian_terminal_id'];
		$pay->merchant_key     = $pay_config['kuaiqian_merchant_key'];
		$pay->cert_pass        = $pay_config['kuaiqian_cert_pass'];

		$this->log_path = $pay->logs_path . 'web_' . date('Y_m_d') . '.log';

		$post_data = $_REQUEST;
		$this->logs('【异步】快钱支付POST内容：' . print_r($post_data, true));
		// 回调数据
		$callback_data = decode(urldecode($_GET['callback_data']));

		$verify_result = $pay->get_callback_params();
		if($verify_result['payResult'] == "10"){
			$this->logs('【异步】验证成功');
			//商户订单号
			$order_sn     = $verify_result['orderId'];
			//交易号
			$trade_no     = $verify_result['dealId'];
			//支付金额,单位为分
			$total_fee    = $verify_result['payAmount'] / 100;
			//卖方账号
			$seller_email = $verify_result['merchantAcctId'];

			$where['order_sn'] = $order_sn;
			$order = D('Order')->where($where)->find();

			//买方支付账号
			$buyer_email = $order['user_id'];
			//买方ID
			$buyer_id    = $order['user_id'];

			if(!$order){
				$this->logs('此订单号不存在！');
				exit("fail");
			}
			if($order['status'] != 'wait_pay'){
				$this->logs('此订单状态不能进行支付，订单状态：' . $order['status'] . '可支付状态：wait_pay');
				//同步跳转到地址
				if($callback_data){
					redirect($callback_data);
				}
				exit("fail");
			}

			$this->logs('提交支付成功订单......');
			//提交订单支付
			D('Order')->order_pay('kuaiqian',
								  $order_sn,
								  $trade_no,
								  $total_fee,
								  $buyer_email,
								  $buyer_id,
								  $seller_email);
			
			$this->logs('支付成功');

			//同步跳转到地址
			if($callback_data){
				redirect($callback_data);
			}
			//支付成功
			exit('<result>1</result><redirecturl></redirecturl>');
		}
		else {
			//验证失败
			$this->logs('验证失败');
			exit("fail");
		}
	}
	//写入日志
	protected function logs($content){
		\Think\Log::write($content, \Think\Log::INFO, '',$this->log_path);
	}
}
?>